package com.lichuandi.crawler;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/weather")
public class WeatherController {

    @GetMapping("/forecast")
    public String getWeatherForecast() {
        try {
            String url = "http://api.ipshudi.com/weather/"; // 要爬取的天气网站URL
            //Document document = Jsoup.connect(url).get();
            Document document = Jsoup.connect(url).ignoreContentType(true).userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)")
                    .timeout(5000).get();

            Elements forecasts = document.select(".forecast-item"); // 获取天气预报的元素
            StringBuilder result = new StringBuilder();

            for (Element forecast : forecasts) {
                String date = forecast.select(".date").text(); // 获取日期
                String weather = forecast.select(".weather").text(); // 获取天气情况
                String temperature = forecast.select(".temperature").text(); // 获取温度

                result.append(date).append(": ").append(weather).append(", ").append(temperature).append("\n");
            }

            return result.toString();
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }
}
